import 'dart:ui';

import 'package:flutter/material.dart';
import 'verification_cursor.dart';

/// 输入框样式
enum VerificationItemType {
  ///下划线
  underline,

  /// 盒子
  box,
}

/// 单个输入框
class VerificationItem extends StatelessWidget {
  VerificationItem(
      {this.type = VerificationItemType.box,
      this.text,
      this.textStyle,
      this.decoration,
      this.showCursor = true,
      this.cursorColor = Colors.black45,
      this.cursorWidth = 2,
      this.cursorDecoration,
      this.width = 48,
      this.height = 48});

  // 类型
  final VerificationItemType type;
  // 文本相关
  final String text;
  final TextStyle textStyle;

  // 盒子相关
  final double width;
  final double height;
  final Decoration decoration;

  // 光标相关
  final bool showCursor;
  final Color cursorColor;
  final double cursorWidth;
  final Decoration cursorDecoration;

  @override
  Widget build(BuildContext context) {
    Color _borderColor = Theme.of(context).dividerColor;
    double _borderWidth = 2;
    TextStyle _textStyle = textStyle ?? TextStyle(fontSize: 24);
    Function widgetFun;
    Text text = _buildText(_textStyle);
    if (type == VerificationItemType.box) {
      widgetFun = _buildBoxDecoration(text, _borderColor, _borderWidth);
    } else {
      widgetFun = _buildUnderlineDecoration(text, _borderColor, _borderWidth);
    }
    return widgetFun(Row(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        _buildText(_textStyle),
        showCursor
            ? VerificationCursor(
                width: cursorWidth ?? 2,
                height: _textStyle.fontSize,
                color: cursorColor ?? Theme.of(context).cursorColor,
                decoration: cursorDecoration)
            : SizedBox.shrink()
      ],
    ));
  }

  /// 绘制盒子类型
  _buildBoxDecoration(Text text, [Color borderColor, double borderWidth]) {
    return (Widget child) => Container(
          width: width,
          height: height,
          alignment: Alignment.center,
          decoration: decoration ??
              BoxDecoration(
                  border:
                      Border.all(color: borderColor, width: borderWidth ?? 2)),
          child: child,
        );
  }

  /// 绘制下划线类型
  _buildUnderlineDecoration(Text text,
      [Color borderColor, double borderWidth]) {
    return (Widget child) => Container(
          width: width,
          height: height,
          alignment: Alignment.center,
          decoration: UnderlineTabIndicator(
              borderSide:
                  BorderSide(color: borderColor, width: borderWidth ?? 2)),
          child: text,
        );
  }

  /// 文本
  _buildText(textStyle) {
    return Text(
      '$text',
      style: textStyle,
    );
  }
}
